<!-- src/components/Register.vue -->
<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-left">
        <div class="welcome-content">
          <h1>欢迎加入</h1>
          <p>请输入您的信息完成注册</p>
          <div class="features">
            <div class="feature-item">
              <el-icon><Check /></el-icon>
              <span>安全可靠的账户系统</span>
            </div>
            <div class="feature-item">
              <el-icon><Check /></el-icon>
              <span>隐私保护机制</span>
            </div>
            <div class="feature-item">
              <el-icon><Check /></el-icon>
              <span>快速验证流程</span>
            </div>
          </div>
        </div>
      </div>

      <div class="login-right">
        <el-card class="login-card" shadow="always">
          <div class="login-header">
            <h2>用户注册</h2>
            <p>请填写以下信息以创建账户</p>
          </div>

          <el-form
            class="login-form"
            :model="registerForm"
            :rules="registerRules"
            ref="registerFormRef"
            @submit.prevent="handleRegister"
            size="large"
          >
            <!-- 用户名 -->
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                :prefix-icon="User"
                clearable
              />
            </el-form-item>

            <!-- 邮箱 -->
            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                :prefix-icon="Message"
                clearable
              />
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item prop="mobile">
              <el-input
                v-model="registerForm.mobile"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                clearable
              />
            </el-form-item>

            <!-- 生日 -->
            <el-form-item prop="birthday">
              <el-date-picker
                v-model="registerForm.birthday"
                type="date"
                placeholder="请选择出生日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>

            <!-- 头像 URL -->
            <el-form-item prop="profileUrl">
              <el-input
                v-model="registerForm.profileUrl"
                placeholder="请输入头像链接（可选）"
                :prefix-icon="Picture"
                clearable
              />
            </el-form-item>

            <!-- 密码 -->
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>

            <!-- 确认密码 -->
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                :prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>

            <!-- 英文名 -->
            <el-form-item prop="ename">
              <el-input
                v-model="registerForm.ename"
                placeholder="请输入英文名"
                :prefix-icon="Edit"
                clearable
              />
            </el-form-item>

            <!-- 注册按钮 -->
            <el-form-item>
              <el-button
                class="login-button"
                type="primary"
                :loading="loading"
                @click="handleRegister"
              >
                {{ loading ? '注册中...' : '立即注册' }}
              </el-button>
            </el-form-item>
          </el-form>

          <div class="login-footer">
            <p class="register-tip">
              已有账号？
              <el-link type="primary" :underline="false" @click="$router.push('/login')">
                立即登录
              </el-link>
            </p>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone, Picture, Edit, Check } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

interface RegisterForm {
  username: string
  email: string
  mobile: string
  password: string
  confirmPassword: string
  birthday: string
  profileUrl: string
  ename: string
}

const registerFormRef = ref<InstanceType<typeof ElForm>>()
const loading = ref(false)

const registerForm = reactive<RegisterForm>({
  username: '',
  email: '',
  mobile: '',
  password: '',
  confirmPassword: '',
  birthday: '',
  profileUrl: '',
  ename: ''
})

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '用户名长度在 3 到 12 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  birthday: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  profileUrl: [
    { required: false, message: '请输入头像链接', trigger: 'blur' }
  ],
  ename: [
    { required: true, message: '请输入英文名', trigger: 'blur' }
  ]
}

const handleRegister = async (): Promise<void> => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    loading.value = true

    // 构造请求体 - 关键修复：将 ename 改为 enname
    const requestData = {
      userName: registerForm.username,
      email: registerForm.email,
      mobile: registerForm.mobile,
      password: registerForm.password,
      birthday: registerForm.birthday,
      profileUrl: registerForm.profileUrl || 'https://default-avatar.com/avatar.png',
      createDateTime: new Date().toISOString(),
      updateDateTime: new Date().toISOString(),
      createPerson: 1,
      updatePerson: 1,
      enname: registerForm.ename, // ✅ 修复：改为后端正确的字段名 enname
      isActive: true
    }

    console.log('发送的数据:', requestData)

    // 1. 注册用户
    const response = await axios.post('/api/user', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.operationResult !== 'SUCC') {
      ElMessage.error(response.data.errMsg || '注册失败，请重试')
      return
    }

    ElMessage.success('注册成功！正在为您分配角色...')

    // 2. 查询用户
    let userId: number | null = null
    try {
      const userQueryResponse = await axios.get(`/api/users?username=${registerForm.username}`, {
        headers: {
          'Content-Type': 'application/json'
        }
      })

      const userData = userQueryResponse.data?.data
      if (Array.isArray(userData) && userData.length > 0) {
        userId = userData[0].id
        console.log('获取到用户ID:', userId)
        
        // 验证英文名是否成功保存
        console.log('用户英文名:', userData[0].enname)
      }
    } catch (err) {
      console.error('查询用户失败:', err)
    }

    if (!userId) {
      ElMessage.error('无法获取用户信息，请稍后再试或联系管理员')
      return
    }

    // 3. 绑定角色
    const roleData = {
      roleIds: [3] // 普通用户角色
    }

    const roleResponse = await axios.put(`/api/user_roles/${userId}`, roleData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (roleResponse.data.operationResult === 'SUCC') {
      ElMessage.success('注册成功！已分配普通用户角色。')
    } else {
      ElMessage.warning('注册成功，但角色分配失败：' + (roleResponse.data.errMsg || '未知错误'))
    }

    // 跳转登录页
    router.push('/login')

  } catch (error: any) {
    let message = '注册失败，请检查网络或输入信息'
    if (error.response) {
      const { data } = error.response
      message = data.errMsg || data.error || '请求异常'
    }
    ElMessage.error(message)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
}

.login-wrapper {
  display: flex;
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  min-height: 800px;
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 40px;
  display: flex;
  align-items: center;
}

.welcome-content h1 {
  font-size: 2.5rem;
  margin-bottom: 16px;
  font-weight: 600;
}

.welcome-content p {
  font-size: 1.1rem;
  margin-bottom: 40px;
  opacity: 0.9;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 1rem;
}

.feature-item .el-icon {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 4px;
}

.login-right {
  flex: 1;
  padding: 40px;
  display: flex;
  align-items: center;
}

.login-card {
  border: none;
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  color: #303133;
  font-size: 1.8rem;
  margin-bottom: 8px;
  font-weight: 600;
}

.login-header p {
  color: #909399;
  font-size: 0.9rem;
}

.login-form {
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 1.1rem;
  border-radius: 8px;
}

.login-footer {
  text-align: center;
}

.register-tip {
  color: #909399;
  font-size: 0.9rem;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .login-wrapper {
    flex-direction: column;
    margin: 20px;
  }

  .login-left {
    padding: 40px 20px;
  }

  .login-right {
    padding: 30px 20px;
  }

  .welcome-content h1 {
    font-size: 2rem;
  }
}
</style>